package com.example.sbbsec.web;

import com.example.sbbsec.ConvertUtil;
import com.example.sbbsec.domain.pay.WxPayNotifyService;
import com.example.sbbsec.domain.pay.WxPayService;
import com.example.sbbsec.domain.pay.entity.ExamPayValueObject;
import com.example.sbbsec.domain.pay.entity.WxPayAppRequest;
import com.example.sbbsec.domain.pay.entity.WxPayNotify;
import com.example.sbbsec.domain.pay.entity.WxPayNotifyResponse;
import com.example.sbbsec.domain.pay.entity.WxPayValue;
import com.google.common.io.CharStreams;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static com.google.common.collect.Maps.newHashMap;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author Arat.Wu
 * @date 2018/11/16
 */
@Controller
public class WxPayController {

    private static final Logger LOGGER = getLogger(WxPayController.class);

    private static final Object OBJECT = new Object[0];

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private WxPayNotifyService wxPayNotifyService;
    /**
     * 微信回调接口
     * 如遇网络问题未成功通知微信,则应在下次接受微信回调时告知微信成功信息(未处理)
     * @return String 对微信回调做出响应
     */
    @RequestMapping(value = "1", method = {POST})
    @ResponseBody
    public String getWxPayNotify(HttpServletRequest request) throws IOException {

        final WxPayNotifyResponse wxPayNotifyResponse = new WxPayNotifyResponse();

        try {
            //从请求中获取请求报文
            final String resBody = CharStreams.toString(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));

            LOGGER.info("微信回调信息:{}", resBody);

            //xml转实体
            final WxPayNotify wxPayNotify = ConvertUtil.xmlToObj(resBody, WxPayNotify.class);

            final Map<String,String> objectMap= newHashMap();
            objectMap.put("orderNo",wxPayNotify.getOutTradeNo());
            objectMap.put("resBody",resBody);

            //保存报文 与处理回调事务分离,不一起回滚
            wxPayNotifyService.updateResBody(objectMap);

            //处理回调
            wxPayNotifyService.handleWxPayNotify(wxPayNotify);

            LOGGER.info("微信回调结束,回传告知微信");

        } catch(Exception e) {
            LOGGER.error("微信回调,系统错误:{}", e);
            wxPayNotifyResponse.setReturnCode("FAIL");
        }

        //返回xml字符串
        return ConvertUtil.objToXml(wxPayNotifyResponse);
    }

    /**
     * 小程序服务端预支付
     *
     * @param
     * @return WxPayRequest
     */
    @RequestMapping(value = "2", method = {POST})
    @ResponseBody
    public WxPayAppRequest wxPay(@RequestBody WxPayValue wxPayVO, HttpServletRequest request) {
        LOGGER.info("微信统一支付(预支付请求)开始,小程序请求参数:{}",wxPayVO);
        WxPayAppRequest wxPayAppRequest = null;
        try {

/*            //根据账户获取获取本次缴费信息
            final ExamPayValueObject valueObject;
            //加锁防止用户生成多条缴费信息
            synchronized (OBJECT) {
                valueObject = examService.getExamPaymentByAccId(wxPayVO.getRegId(), wxPayVO.getPayType().getPayType());

                if (valueObject != null) {
                    if (valueObject.getPayOrderId() == null) {
                        //缴费信息不存在新增一个,生成本地订单
                        //final String payOrder = payService.initPayOrder(valueObject.getExamId(), wxPayVO.getPayType().getPayType(), valueObject.getWrittenCharge());
                        valueObject.setPayOrderId(payOrder);
                    }
                }
            }
            //获取ip,文档api中写的必传,但是不传也可以支付
            //wxPayVO.setIpAddress(request.getRemoteAddr());
            //微信预支付开始
            wxPayAppRequest = wxPayService.wxPay(wxPayVO, valueObject);*/
        } catch (Exception e) {
            LOGGER.error("{}", e);
        }
        LOGGER.info("微信统一支付(预支付请求)结束");
        return wxPayAppRequest;
    }

    @RequestMapping(value = "3", method = {POST})
    @ResponseBody
    public void updateWxPayOrderStatusSecond(@PathVariable("orderNo") String orderNo) {
        LOGGER.info("微信小程序页面更新本地订单,订单号{}", orderNo);
        wxPayNotifyService.updateWxPayOrderStatusSecond(orderNo);
    }
}
